<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>07.Controls(PointerLockControls)</title>
    <style>
        body {
            margin: 0;
        }
    </style>
</head>

<body>

    <script type="module">
        import * as THREE from '/build/three.module.js';
        import { PointerLockControls } from '/jsm/controls/PointerLockControls.js';
        //生成场景
        const scene = new THREE.Scene();
        //设置相机
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        camera.position.z = 5;
        //设置渲染器
        const renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);
        //生成模型
        const geometry = new THREE.BoxGeometry();
        const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
        const cube = new THREE.Mesh(geometry, material);
        //设置场景
        scene.add(cube);
        const controls = new PointerLockControls(camera, document.body);
        
        //点击屏幕触发lock
        document.onclick=function(event){
            controls.lock();
        }
        //用键盘控制移动
        document.onkeydown = function (event) { 
                switch (event.key) {  // 获取当前按下键盘键的编码
                    //wsad移动
                    case 'w':
					    controls.moveForward( 0.5 );
                        break;
                    case 's':
                        controls.moveForward( -0.5 );
                        break;
                    case 'a':
                        controls.moveRight( - 0.5 );
                        break;
                    case 'd':
                        controls.moveRight( 0.5 );
                        break;
                
            }
        }
        
        function animate() {
            renderer.render(scene, camera);
            requestAnimationFrame(animate);
        }
        //开始动画
        animate()
    </script>
</body>

</html>